package fm.service.impl;

import fm.dao.HibernateBaseDao;
import fm.entity.VisitorLog;
import fm.service.VisitorLogService;
import fm.util.DateUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;


/**
 * @修改人：CM
 * @修改时间：2017/2/26 0:44
 */
@Service
public class VisitorLogServiceImpl implements VisitorLogService {
    private static final Logger LOGGER = LoggerFactory.getLogger(VisitorLogService.class);

    @Autowired
    HibernateBaseDao baseDao;

    @Override
    public VisitorLog getByIpAndTime(String ip, Date date) {
        return (VisitorLog) baseDao.getUnique("from VisitorLog vl where vl.ip = ? and vl.enterTime>?", ip, DateUtils.getDayStart(date));
    }

    @Override
    public void updateOrAdd(String ip) {
        if (StringUtils.isNotEmpty(ip)) {
            VisitorLog todayLog = getByIpAndTime(ip, new Date(System.currentTimeMillis()));
            if (todayLog != null) {
                todayLog.setLastTime(DateUtils.getTimestamp());
                todayLog.setCount(todayLog.getCount() == null ? 1 : todayLog.getCount() + 1);
                baseDao.update(todayLog);
                LOGGER.info("[{}] 今日第{}次访问本系统", todayLog.getIp(), todayLog.getCount());

            } else {
                todayLog = new VisitorLog();
                todayLog.setLastTime(DateUtils.getTimestamp());
                todayLog.setCount(todayLog.getCount() == null ? 1 : todayLog.getCount() + 1);
                todayLog.setEnterTime(DateUtils.getTimestamp());
                todayLog.setIp(ip);
                baseDao.save(todayLog);
                LOGGER.info("[{}] 今日第一次访问本系统", ip);
            }
        }
    }

    @Override
    public long todayVisitor() {
        String hql = "select count(vl.id) from VisitorLog vl where vl.enterTime>?";
        return ((Long) baseDao.getHibernateTemplate().getSessionFactory().getCurrentSession().createQuery(hql).setTimestamp(0, DateUtils.getDayStart(new Date())).uniqueResult());
    }
}
